package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.activity.toJSONString
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.ParamsDTO
import com.abc.robot01.retrofit.bean.RenderPaymentRequest
import com.abc.robot01.retrofit.bean.RenderPaymentRequest2
import com.abc.robot01.retrofit.bean.RequestData
import com.abc.robot01.retrofit.bean.UserOrderDetailDTO
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

class ZhifuViewModel : ViewModel() {
    val TAG = "ZhifuViewModel"
    val show =
        mutableStateOf(true)

    val userName = mutableStateOf("")
    val customerPhone = mutableStateOf("")
    val designPackageId = mutableStateOf("")
    val housePlansId = mutableStateOf("")
    val housePlanDataId = mutableStateOf("")
    val fee = mutableStateOf("0.0")
    val name = mutableStateOf("")
    val paymentMethod = mutableStateOf(-1)
    val renderRoomIds = mutableListOf<String>()
    val skyBoxId = mutableStateOf("")

    val paySuccess = mutableStateOf(false)

    var base64 by mutableStateOf(
        "iVBORw0KGgoAAAANSUhEUgAAASkAAAEpCAYAAADPmdSCAAAD40lEQVR4nO3UMQEAIAzAMMC/5+GAlx6Jgl7dM7MAqs7vAIAXkwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIO0CI1AFT7xPGE4AAAAASUVORK5CYII=\n"
    )

    private fun wechatPay(){
        //发起异步任务
        viewModelScope.launch {
            //授权成功,保存户型数据(渲染支付前调用)
            val s = RetrofitService.instance.housePlanData(
                userId=Robot.userId,
                accessToken = Robot.accessToken,
                request = RenderPaymentRequest2(
                    id = housePlanDataId.value,
                    housePlanId = housePlansId.value,
                    name = "",
                    skyBoxId = skyBoxId.value.also {
                        Log.e(TAG, "保存户型数据 天空盒 ID:" + it)
                    }
                ).also {
                    Log.e(TAG, "保存户型数据1028 参数:" + it)
                }
            )
            Log.e(TAG, "保存户型数据:" + s)
            if (s.code == 200 && s.message == "success") {
                Log.e(TAG, "保存户型数据成功:" + s)
            }
            // 开始支付
            val totalAmount = fee.value.toDouble()
//            val totalAmount = 0.01
            val  request = RenderPaymentRequest(userId = Robot.userId,
                companyId = Robot.companyId,
                purseType =  "PERSONAL",
                totalAmount = totalAmount,
                robotId = Robot.robotId,
                customerName = userName.value,
                renderName = name.value,
                customerPhone = customerPhone.value,
                userOrderDetailDTOList = listOf(
                    UserOrderDetailDTO(
                        // 产品类型：1 精品方案, 2 分部方案, 3 模型, 4 贴图, 5 材质, 6 户型图, 7 渲染, 8 任务, 9 服务, 10 充值, 11 提现, 12 产品包购买
                        productType = 7,
                        productUserId = Robot.userId,
                        productCompanyId = Robot.companyId,
                        productId = designPackageId.value,
                        detail = Detail(
                            renderRoomIds = renderRoomIds,
                            housePlansId = housePlansId.value,
                            housePlanDataId = housePlanDataId.value
                        ).toJSONString().also {
                            Log.e(TAG, "Detail:" + it)
                        },
                        productAmount = totalAmount
                    )
                ).also {
                    Log.e(TAG, "渲染支付  :request:" + it)
                }
            )

            Log.e(TAG, "recharge:" + request)
            val res = RetrofitService.instance.wechatPay(
                accessToken = Robot.accessToken,
                userId = Robot.userId,
                companyId = Robot.companyId,
                "WECHAT_NATIVE",
                request
            )
            Log.e(TAG, "微信支付:" + res)
            base64 = res.data.qrCode

            val  userOrderId =  res.data.userOrderId
//            if(1==1) return@launch

            val r = asyncTaskAsyncTask(type = 6,userOrderId=userOrderId)
            if (r.not()) return@launch
//                开始轮循,只有成功才返回
            val userId = poll("6")
            if(userId=="-1"){
                Log.e(TAG, "支付失败")
                show.value = false
                paySuccess.value = false
                return@launch
            }

            Log.e(TAG, "支付结果:" + res)
            if (res.code==200 && res.message == "success") {
                paySuccess.value = true
                show.value = false
            } else if (res.code == 400) {
                Log.e(TAG, "余额不足")
                paySuccess.value = false
//                fail.value = true
                show.value = false
            }
        }
    }
    fun  startPay() {
        if (paymentMethod.value == -1)
            throw IllegalStateException()

        if (paymentMethod.value == 2) wechatPay()
        else {
            //发起异步任务
            viewModelScope.launch {
                val r = asyncTaskAsyncTask()
                if (r.not()) return@launch

                //生成小程序码
                base64 = genMiniProgramQrCode()

//                开始轮循,只有成功才返回
                val userId = poll()

                if (userId == "-1") {
                    Log.e(TAG, "支付失败")
                    show.value = false
                    paySuccess.value = false
                    return@launch
                }


                //授权成功,保存户型数据(渲染支付前调用)
                val s = RetrofitService.instance.housePlanData(
                    userId = Robot.userId,
                    accessToken = Robot.accessToken,
                    request = RenderPaymentRequest2(
                        id = housePlanDataId.value,
                        housePlanId = housePlansId.value,
                        name = "",
                        skyBoxId = skyBoxId.value.also {
                            Log.e(TAG, "保存户型数据 天空盒 ID:" + it)
                        }
                    ).also {
                        Log.e(TAG, "保存户型数据1028 参数:" + it)
                    }
                )

                Log.e(TAG, "保存户型数据:" + s)
//            val a1 = JSONObject(s);
                if (s.code == 200 && s.message == "success") {
                    Log.e(TAG, "保存户型数据成功:" + s)
                }

                // 开始支付
                val totalAmount = fee.value.toDouble()

                Log.e(TAG, "渲染支付  :companyId:" + Robot.companyId)
                val res = RetrofitService.instance.renderPay(
                    Robot.accessToken, companyId = Robot.companyId,
                    userId = userId,
                    request = RenderPaymentRequest(userId = userId,
                        companyId = Robot.companyId,
                        totalAmount = totalAmount,
                        robotId = Robot.robotId,
                        customerName = userName.value,
                        renderName = name.value,
                        customerPhone = customerPhone.value,
                        userOrderDetailDTOList = listOf(
                            UserOrderDetailDTO(
                                // 产品类型：1 精品方案, 2 分部方案, 3 模型, 4 贴图, 5 材质, 6 户型图, 7 渲染, 8 任务, 9 服务, 10 充值, 11 提现, 12 产品包购买
                                productType = 7,
                                productUserId = Robot.userId,
                                productCompanyId = Robot.companyId,
                                productId = designPackageId.value,
                                detail = Detail(
                                    renderRoomIds = renderRoomIds,
                                    housePlansId = housePlansId.value,
                                    housePlanDataId = housePlanDataId.value
                                ).toJSONString().also {
                                    Log.e(TAG, "Detail:" + it)
                                },
                                productAmount = totalAmount
                            )
                        ).also {
                            Log.e(TAG, "渲染支付  :request:" + it)
                        }
                    )
                )
                Log.e(TAG, "支付结果:" + res)
                if (res.code == 200 && res.message == "success") {
                    paySuccess.value = true
                    show.value = false
                } else if (res.code == 400) {
                    Log.e(TAG, "余额不足")
                    paySuccess.value = false
//                fail.value = true
                    show.value = false
                }
            }
        }
    }

    data class Detail(
        val housePlansId: String,
        val housePlanDataId: String,
        val renderRoomIds: List<String>
    )
}

fun generateRandomId(length: Int = 8): String {
    val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    return (1..length)
        .map { allowedChars.random() }
        .joinToString("")
}

///**
// *  发起异步任务
// *  // 业务数据类型(使用数字) 1 扫码登录及注册，2 校验超管权限，3 校验用户归属公司，
// * 	// 4 上传户型图， 5 分享，6 支付
// */
//suspend fun asyncTaskAsyncTask(type: Int = 3): Boolean {
//    Robot.randomId = generateRandomId()
//    Log.e("asyncTaskAsyncTask", "发起异步任务 rid:" + Robot.randomId)
//    val res = RetrofitService.instance.asyncTask(
//        RequestData(
//            sn = Robot.sn,
//            type = type,
//            rid = Robot.randomId,
//            paramsDTO = ParamsDTO()
//        )
//    )
//
//    val code =res.code
//    if (code != 200) {
//        Log.e("asyncTaskAsyncTask", "发起异步任务失败")
//        return false
//    }
//    Log.e("asyncTaskAsyncTask", "发起异步任务成功:"+res)
//    return true
//}

/**
 * 轮循
 */
suspend fun poll(type: String ="3"): String {
    while (true) {
        delay(2000)
        val a = RetrofitService.instance.pullAsyncTask(
            type =type,
            sn = Robot.sn,
            rid = Robot.randomId,
            accessToken = Robot.accessToken
        )

        Log.e("PULL", "轮循支付结果:" + a)
        Log.e("PULL", "轮循支付结果:" + a.data.status)
        if (a.data.status == "PROCESS") {
            Log.e("PULL", "还在处理:")
        }
        else if (a.data.status == "FAILURE") {
            Log.e("PULL", "支付失败:")
            return  "-1"
        }
        else {
            Log.e("PULL", "授权成功")
            Log.e("PULL", " a.data.resultDTO.userId: " + a.data.resultDTO.userId)
            return a.data.resultDTO.userId;
        }
    }
}

/**
 *   员工管理 使用2
 *   申请管理使用 2
 */
suspend fun genMiniProgramQrCode(type:String="3"): String {
    val TAG = "生成小程序码"
    val res2 = RetrofitService.instance.genMiniProgramQrCode(
        accessToken = Robot.accessToken.also {
            Log.e(TAG, "accessToken:" + it)
            Log.e(TAG, "sn:" + Robot.sn)
            Log.e(TAG, "randomId:" + Robot.randomId)
        },
        type = type,
        sn = Robot.sn,
        rid = Robot.randomId,
    )
    val data = res2.data
    Log.e(TAG, "生成小程序码:" + res2)
    Log.e(TAG, "生成小程序码:" + data)
    return data
}
